package oss

import (
	"app/common/funcs"
	"app/pkg/config"
	fileTools "app/pkg/file"
	httpUtil "app/pkg/http"
	"bytes"
	"context"
	"time"

	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
)

type QnOss struct {
}

func NewQnOss() *QnOss {
	return &QnOss{}
}

func (m *QnOss) PreviewUrl(path string) string {
	return config.Config.Credential.Qiniu.FinalHost + "/" + path
}

func (m *QnOss) PutImage(dstName, originUrl string, headers map[string]string) error {
	putPolicy := storage.PutPolicy{
		Scope: config.Config.Credential.Qiniu.Bucket,
	}
	mac := qbox.NewMac(config.Config.Credential.Qiniu.AccessKeyID, config.Config.Credential.Qiniu.AccessKeySecret)
	upToken := putPolicy.UploadToken(mac)
	cfg := storage.Config{}
	// 是否使用https域名
	cfg.UseHTTPS = false
	// 上传是否使用CDN上传加速
	cfg.UseCdnDomains = false
	formUploader := storage.NewFormUploader(&cfg)
	// rstBytes, err := httpUtil.Get(originUrl, map[string]string{"Referer": "https://movie.douban.com/"}, 5)
	rstBytes, err := httpUtil.Get(originUrl, headers, 5)
	if err != nil {
		return err
	}
	dataLen := int64(len(rstBytes))
	err = formUploader.Put(context.Background(), &storage.PutRet{}, upToken, dstName, bytes.NewReader(rstBytes), dataLen, &storage.PutExtra{})
	return err
}

func (m *QnOss) PutImageBytes(dstName string, data []byte) error {
	putPolicy := storage.PutPolicy{
		Scope: config.Config.Credential.Qiniu.Bucket,
	}
	mac := qbox.NewMac(config.Config.Credential.Qiniu.AccessKeyID, config.Config.Credential.Qiniu.AccessKeySecret)
	upToken := putPolicy.UploadToken(mac)
	cfg := storage.Config{}
	// 是否使用https域名
	cfg.UseHTTPS = false
	// 上传是否使用CDN上传加速
	cfg.UseCdnDomains = false
	formUploader := storage.NewFormUploader(&cfg)
	dataLen := int64(len(data))
	err := formUploader.Put(context.Background(), &storage.PutRet{}, upToken, dstName, bytes.NewReader(data), dataLen, &storage.PutExtra{})
	return err
}

// 上传网络图片
func (m *QnOss) PutNetImage(poster string, headers map[string]string) (pic string, err error) {
	dstName := "kiko/" + time.Now().Format("20060102") + "/" + funcs.GenRandomString(32) + "." + fileTools.GetExt(poster)
	pic = m.PreviewUrl(dstName)
	err = m.PutImage(dstName, poster, headers)
	return
}
